<?php
// +----------------------------------------------------------------------
// | Author: fulei <365581323@qq.com>
// +----------------------------------------------------------------------
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{	
	//定义常量
    const OK=200; //成功
    const ERROR=500;  //失败 
    //获取优惠券信息
    public function index()
    {
        $data=Db::name('coupon')->select();
        if($data){//存在
            return json_encode(array(
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ));
           }else{//不存在
            echo self::THORW_ERROR("没有找到相关信息");
           }
           return $data;
    }
    //轮播图
    public function banner()
    {
        $data=Db::name('banner')->select();
        if($data){//存在
            return json_encode(array(
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ));
           }else{//不存在
            echo self::THORW_ERROR("暂时没有轮播图");
           }
           return $data;
    }
    //热卖推荐
    public function hotgoods()
    {   
        $data=Db::table('xcx_goods')->where("gcate=2")->select();
        if($data){//存在
            return json_encode(array(
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ));
           }else{//不存在
            echo self::THORW_ERROR("暂时没有热卖推荐");
           }
           return $data;
    }
    //商品品牌
    public function brand(){
        $data=Db::table('xcx_brand')->order('bid desc')->select();
        if($data){//存在
            return json_encode(array(
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                )); 
           }else{//不存在
            echo self::THORW_ERROR("获取商品品牌失败");
           }
           return $data;
    }
    //商品信息
    public function getgoods(){
        $gbrand = input('bid');
        $gid = input('gid');
        if($gid){
            $data=Db::name('goods')->where('gid='.$gid)->select();
        }else{
            $data=Db::name('goods')->where('gbrand='.$gbrand)->select();
        }
        if($data){//存在
            return json_encode(array(
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ));
           }else{//不存在
            echo self::THORW_ERROR("获取该品牌下商品失败");
           }
    }
    //对应规格下的商品
    public function goods(){
        $gbrand = input('gbrand');
        $data=Db::name('goods')->where('gbrand='.$gbrand)->select();
     
        if($data){//存在
                 foreach ($data as $k => $v) 
                {

                    if(mb_strlen($v['gtitle'],'utf8') > 12)
                    {
                        $data[$k]['gtitle']=subtext($v['gtitle']);
                    }
                    
                }
            return json([
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ]);
           }else{//不存在
            echo self::THORW_ERROR("获取该品牌下商品失败");
           }
    }
    //添加地址
    public function addaddress(){
        $ausername = input('ausername');
        $openid = input('openid');
        $amobile = input('amobile');
        $area = input('area');
        $addresss = input('addresss');
        $data =array(
            'ausername' => $ausername,
            'aopenid' => $openid,
            'amobile' => $amobile,
            'area' => $area,
            'addresss' => $addresss
            );
        $address=Db::name('address')->insert($data);
    }
    //查询地址
    public function getaddress(){
        $aopenid = input('aopenid');
        $data=Db::name('address')->where("aopenid='$aopenid'")->order('starts desc')->select();
        if($data){//存在
            return json_encode(array(
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ));
           }else{//不存在
            echo self::THORW_ERROR("获取地址失败");
           }
    }
    //根据aid获取地址
    public function updaddress(){
         $aid = input('aid');
         $aopenid = input('aopenid');
         $data=Db::name('address')->where("aopenid='$aopenid'")->where("aid='$aid'")->select();
         if($data){//存在
            return json_encode(array(
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ));
           }else{//不存在
            echo self::THORW_ERROR("获取地址失败");
           }
    }
    //修改地址
    public function updateaddress(){
        $aid = input('aid');
        $ausername = input('ausername');
        $openid = input('openid');
        $amobile = input('amobile');
        $area = input('area');
        $addresss = input('addresss');
        $data =array(
            'ausername' => $ausername,
            'aopenid' => $openid,
            'amobile' => $amobile,
            'area' => $area,
            'addresss' => $addresss
            );
        $address=Db::name('address')->where("aid='$aid'")->where("aopenid='$openid'")->update($data);
    }
    //删除地址
    public function deladdress(){
        $aid = input('aid');
        $openid = input('openid');
        $data = array(
            'aid' => $aid
            );
        Db::name('address')->where("aid='$aid'")->where("aopenid='$openid'")->delete($data);
    }
    //查询规格
    public function specs(){
        $gid = input('gid');
        $data=Db::name('specs')->where("sgoods=".$gid)->select();
        if($data){//存在
            return json_encode(array(
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ));
           }else{//不存在
            echo self::THORW_ERROR("该商品暂时没有设定规格");
           }
           return $data;
    }


    //加入购物车
    public function addshoporder(){
        $openid = input('openid');//商户openid
        $gtitle = input('gtitle');//标题
        $goodid = input('gid');//商品id
        $spec = input('spec');//商品规格
        $price = input('price');//商品单价
        $num = input('onum');//购买数量
        $map=array('openid'=>$openid,'goodid'=>$goodid,'spec'=>$spec);

        $find=Db::name('shopgoods')->where($map)->find();//查询相同商品相同规格是否添加过

        if($find){//存在，在原来基础上增加数量

            $data['num']=$find['num']+$num;

            Db::name('shopgoods')->where('id='.$find['id'])->update($data);

        }else{//不存在 新建数据
            $data =array(
            'openid' => $openid,
            'title' => $gtitle,
            'goodid' => $goodid,
            'spec' => $spec,
            'num' => $num,
            'price' => $price,
            );
        Db::name('shopgoods')->insert($data);
        }
        
    }
    //立即购买添加记录
    public function addbuynow(){
        $openid = input('openid');//商户openid
        $dtitle = input('gtitle');//标题
        $dgoodid = input('gid');//商品id
        $dspec = input('spec');//商品规格
        $dprice = input('price');//商品单价
        $dnum = input('onum');//购买数量
        $ousername = input('ousername');//收件人
        $omobile = input('omobile');//联系电话
        $area = input('area');//区域地址
        $address = input('oaddress');//收货地址
        $oaddress =$area.$address;
        $ofare = input('ofare');//运费
        $order_sn = "SC_".time().rand(11111,99999);//订单号
        $addtime = time();//添加时间
        $opaymoneys = $dprice*$dnum+$ofare;
        $addtime = time();//添加时间
        $opaymoneys = $dprice*$dnum+$ofare;
        //通过openid查询领取优惠券表,是否有优惠券,如果有用$opaymoney比较优惠范围
 
        //查询地址
        if(empty($ousername)&empty($omobile)&empty($oaddress)){
            $address=Db::name('address')->where("aopenid='$openid'")->find();
            $ousername =$address['ausername'];
            $omobile = $address['amobile'];
            $area = $address['area'];
            $address = $address['addresss'];
            $oaddress =$area.$address;
        }
        $countmoney = $dprice*$dnum+$ofare;//商品总价=商品单价*购买数量+运费-优惠券
        //添加数据到商品订单表中
        $data =array(
            'dopenid' => $openid,
            'dtitle' => $dtitle,
            'dgoodid' => $dgoodid,
            'dspec' => $dspec,
            'dnum' => $dnum,
            'dprice' => $dprice,
            );
        $arr=Db::name('ordergoods')->insertGetId($data);//返回添加的商品订单的id
         $data1 = array(
            'ousername' => $ousername,
            'omobile' => $omobile,
            'oaddress' => $oaddress,
            'ogoods' => $arr,
            'ofare' => $ofare,
            'order_sn' => $order_sn,
            'oaddtime' => $addtime,       
            'opaymoney' => $countmoney,
            'oopenid' => $openid
            );
       $list=Db::name('orders')->insertGetId($data1);
       return $list;

    }
    //查找订单
    public function selectgoodsorders(){
        $oid =input('oid');
        // $data=Db::name('orders')->where("oopenid='$openid'")->where("oid='$oid'")->find();
        $data=Db::table('xcx_orders')->alias('a')->join('xcx_ordergoods w','a.ogoods = w.did','left')->where("oid='$oid'")->find();
        if($data){//存在
            return json([
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ]);
           }else{//不存在
            echo self::THORW_ERROR("还没有订单");
           }
    }
    //我的订单*待付款
    public function waitpay(){
         $ostarts = input('ostarts','0');
         $openid = input('openid');
         $list=Db::name('orders')->where("ostarts=".$ostarts)->where("oopenid='$openid'")->order("oid desc")->select();
         $redata=array();
         foreach ($list as $k => $v) {
            $aid = explode(',',trim($v['ogoods'],','));
            // print_r($aid);
            $where['did'] = array('in',$aid);

            $data=Db::name('ordergoods')->where($where)->select();
            foreach ($data as $k=> $val) {
            $picurl=Db::name('goods')->where('gid='.$val['dgoodid'])->field('goodsthumb')->find();
            $data[$k]['picurl']=$picurl['goodsthumb'];
            }
            $bfdata['oid'] = $v['oid'];
            $bfdata['order_sn'] = $v['order_sn'];
            $bfdata['opaymoney'] = $v['opaymoney'];
            $bfdata['data']=$data;
            array_push($redata,$bfdata);
         }
         return json_encode($redata);
    }
    //购物车订单
    public function shopping(){
         $openid = input('openid');
        $data=Db::table('xcx_shopgoods')->alias('a')->join('xcx_goods w','a.goodid = w.gid','left')->where("openid='$openid'")->select();
        $arr = array();
        foreach ($data as  $value) {
            $value['type']="编辑";
            $arr[] = $value;
        }
        if($arr){//存在
            return json([
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$arr
                ]);
           }else{//不存在
            echo self::THORW_ERROR("没找到该订单");
           }
    }
	  //删除购物车订单
    public function delShopOrder(){
        $oid = input('oid');
        $openid = input('openid');
        $data =array(
            'oid' => $oid
            );
        Db::name('shopgoods')->where("id='$oid'")->where("openid='$openid'")->delete($data);
    }
    //删除订单
    public function delorders(){
        $oid = input('oid');
        $openid = input('openid');
        $data =array(
            'oid' => $oid
            );
        Db::name('orders')->where("oid='$oid'")->where("oopenid='$openid'")->delete($data);
    }
    //确认订单
     public function updstarts(){
        $oid = input('oid');
        $openid = input('openid');
        $data =array(
            'ostarts' => 3
            );
        Db::name('orders')->where("oid='$oid'")->where("oopenid='$openid'")->update($data);
    }
    //修改默认地址
    public function trueaddress(){
        $aopenid = input('aopenid');
        $aid = input('aid');
        $data = array(
            'aid' => $aid,
            'starts' => 1
            );
        $cate = array(
            'starts' => 0
            );
        Db::name('address')->where("aopenid='$aopenid'")->update($cate);
        Db::name('address')->where("aid='$aid'")->where("aopenid='$aopenid'")->update($data);
        }
    //添加用户信息
    public function adduser(){
        $unickname = input('unickname');
        $usex = input('usex');
        $uopenid = input('uopenid');
        $uaddtime = time();
        $data = array(
            'unickname' => $unickname,
            'uopenid' => $uopenid,
            'usex' => $usex,
            'uaddtime' => $uaddtime
            );
			
		if(!empty($data['uopenid'])){	
			$list=Db::name('user')->where("uopenid='$uopenid'")->select();
			if(empty($list)){
				Db::name('user')->insert($data);

			}
		}
    }
    //搜索商品
    public function seargoods(){
        $gtitle = input('gtitle');
        if($gtitle){
            $data=Db::name('goods')->where("gtitle","like","%".$gtitle."%")->select();
        }else{
            $data=Db::name('goods')->select();
        }
        if($data){//存在
            foreach ($data as $k => $v) {
                $data[$k]['goodshow']=explode("|",rtrim($v['goodshow'],'|'))[0];
            }
            return json([
                'code'=>self::OK,
                'mess'=>'ok',
                'data'=>$data 
                ]);
           }else{//不存在
            echo self::THORW_ERROR("没有商品");
           }
    }
    //提交订单显示页
	public function placeOrder()
	{
		$id = input('id');
		$openid = input('openid');
		$opaymoney = input('allprice');
		$aid = explode(',',trim($id,','));
        // print_r($aid);
        $where['id'] = array('in',$aid);
        $data=Db::name('shopgoods')->where($where)->select();
		foreach($data as $k=>$v)
		{
			$goods=Db::name('goods')->where('gid='.$v['goodid'])->field('goodsthumb')->find();
			$data[$k]['picurl']=$goods['goodsthumb'];
			
		}
		
        //$data=Db::name('shopgoods')->where($where)->select();
		$fare=array();
		
		$fare=Db::table('xcx_shopgoods')->alias('a')->join('xcx_goods w','a.goodid = w.gid','left')->where($where)->order('gfare desc')->find();
		$gfare=$fare['gfare'];
		//print_R($gfare);
		  //优惠券信息
       
		$redata['opaymoney']=$opaymoney;
        $redata['goods']=$data;
      
        $redata['ofare']=$gfare;
		echo json_encode($redata);
		
	}
    //修改购物车数量
	public function saveNum()
	{
		
		$id=input("id");
		$data['num']=input("num");
		if($data['num']>0){
			Db::name("shopgoods")->where("id=".$id)->update($data);
		}
	}
    public function getshoporder(){
		
        $id = input('id');
        $openid = input('openid');
        $ousername = input('ausername');
        $omobile = input('amobile');
        $area = input('area');
        $addres = input('addresss');
        $oaddress = $area.$addres;
        $order_sn = "SC_".time().rand(11111,99999);
        $opaymoney = input('allprice');
        $aid = explode(',',trim($id,','));
      //  print_r($aid);exit;
        $where['id'] = array('in',$aid);
        $data=Db::name('shopgoods')->where($where)->select();
 
        $cate=",";
        $alldata=array();
        foreach ($data as $val) {
            $ins = array(
            'dgoodid' => $val['goodid'],
            'dtitle' => $val['title'],
            'dspec' => $val['spec'],
            'dnum' => $val['num'],
            'dprice' => $val['price'],
            'dopenid' => $val['openid']
            );
          
            $cate.=Db::name('ordergoods')->insertGetId($ins).','; 
            $picurl=Db::name('goods')->where('gid='.$val['goodid'])->field('goodsthumb')->find();
            $ins['picurl']=$picurl['goodsthumb'];
            array_push($alldata, $ins);
            //删除购物订单表数据
            $del = array(
                'id' => $val['id']
                );
            Db::name('shopgoods')->where("id=".$val['id'])->delete($del);
        }
	
       // return $cate;
       // $arr['ogoods']=$cate;
       //获得邮费
       $cid = explode(',',trim($cate,','));
        // print_r($aid);
        $w['did'] = array('in',$cid);
        $fare=Db::table('xcx_ordergoods')->alias('a')->join('xcx_goods w','a.dgoodid = w.gid','left')->where($w)->order('gfare desc')->find();
        $ofare =$fare['gfare'];
       //优惠券信息
    
        $paymoney=$opaymoney+$ofare;
       $arr =array(
            'ousername' => $ousername,
            'omobile' => $omobile,
            'oaddress' => $oaddress,
            'order_sn' => $order_sn,
            'ogoods' => $cate,
            'oaddtime' => time(),
            'ofare' => $ofare,
           
            'opaymoney' => $paymoney,
            'oopenid' => $openid
        );
       $getoid=Db::name('orders')->insertGetId($arr);

        $redata['order_sn']=$order_sn;
        $redata['opaymoney']=$opaymoney;
        $redata['goods']=$alldata;
 
        $redata['ofare']=$ofare;
		$redata['total_fee']=$paymoney;
       return json_encode($redata);
    }
		//重新选择地址后，对订单进行修改
		public function saveOrderAdress()
		{
			$msg['out_trade_no']='SC_149977158158354';
			$data['ostarts']=1;
			$save= Db::name('orders')->where("order_sn='".$msg['out_trade_no']."'")->update($data); 
			echo Db::name('orders')->getlastsql();
		}
    //回调
    public function notify(){ 
			
			$xml = file_get_contents("php://input");
            $fp = fopen('log.txt',"a");
            flock($fp, LOCK_EX) ;
            fwrite($fp,"执行日期：".date('Y-m-d H:i')."\n".$xml."\n\n");
            flock($fp, LOCK_UN);
            fclose($fp);
            //xml转数组
			
			$msg = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
			
			if($msg['result_code']=='SUCCESS' && $msg['return_code']=='SUCCESS')
			{
				
				 $data['ostarts']=1;
				 $save= Db::name('orders')->where("order_sn='".$msg['out_trade_no']."'")->update($data); 
				 if($save)
				 {
					echo "SUCCESS"; 
				 }
				  
			}
			
    }

    /*静态抛出错误*/
    function THORW_ERROR($mess="参数错误"){
        return json_encode(
            array(
            'code'=>self::ERROR,
            'mess'=>$mess,
            'data'=>""
            )
            );
    }
    // 以POST方式提交数据
    public function post_data($url, $param=null, $is_file = false, $return_array = true) {
        if (! $is_file && is_array ( $param )) {
          $param = JSON ( $param );
        }
        if ($is_file) {
          $header [] = "content-type: multipart/form-data; charset=UTF-8";
        } else {
          $header [] = "content-type: application/json; charset=UTF-8";
        }
        
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
        curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $param );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        $res = curl_exec ( $ch );
        
        $flat = curl_errno ( $ch );
        if ($flat) {
          $data = curl_error ( $ch );
        }
        
        curl_close ( $ch );
        
        $return_array && $res = json_decode ( $res, true );
        
        return $res;
      }
     public  function tesss()
      {
        $str="中国是一个很神奇的国家啊啊啊啊啊啊啊啊啊啊啊啊啊";
        if(mb_strlen($str, 'utf8') > 15)
        {
            $str=subtext($str);
        }
        echo $str;
      }
       public function getOpenid()
      {
          $code = trim($_GET['code']);
            if($code)
            {
                $appid = "wxf56864238b4b5ae8";
                $secrect = "e6d073ee0b148ccdd8c0e75509ef61b3";
                $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secrect."&js_code=".$code."&grant_type=authorization_code";
                
                echo file_get_contents($url);exit;
                
            }

      }
}
